package cn.youdian.web.controller;

import cn.youdian.data.entity.Category;
import cn.youdian.data.entity.Product;
import cn.youdian.web.model.CategoryModel;
import cn.youdian.web.model.ProductModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import cn.youdian.service.CategoryService;
import cn.youdian.service.ProductService;

import java.util.ArrayList;
import java.util.List;

/**
 * 案例/产品控制器
 *
 * @author K.J
 * @date 2021.06.06 21:56:17
 */
@RestController
public class ProductController extends BaseController {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private ProductService productService;

    @GetMapping("/products")
    public ModelAndView products(@RequestParam(value = "category_id", defaultValue = "1") Long categoryId) {
        ModelAndView view = new ModelAndView("products");
        Long ncategoryId = categoryId == 0 ? 1 : categoryId;
        List<Category> categorys = categoryService.all();
        List<Product> products = productService.listByCategory(categoryId);

        List<CategoryModel> categoryModelList = new ArrayList<>();
        categorys.forEach(c -> {
            categoryModelList.add(new CategoryModel(c.getId(), c.getUserName(), (c.getId().equals(ncategoryId) ? true : false)));
        });

        List<ProductModel> productModelList = new ArrayList<>();
        products.forEach(p -> productModelList.add(new ProductModel(p.getId(), p.getCategoryId(), p.getProductName(), p.getProductDesc(), p.getProductThum())));
        view.addObject("categorys", categoryModelList);
        view.addObject("products", productModelList);
        return view;
    }
}
